#include <qqml.h>
#include <QQmlContext>
#include <private/qobject_p.h>
#include "AnimMontageUtils.h"
static void groupByIdImp(QObject* root,QMap<QString,QObject*>& ret){
    if(!root)
    {
        return ;
    }
    auto ctx = qmlContext(root);

    if(ctx)
    {
        QString id = ctx->nameForObject(root);
        if(!id.isEmpty())
        {
            ret[id] = root;
        }

    }

    for(auto i:root->children())
    {
        groupByIdImp(i,ret);
    }
}

AnimMontageUtils::IdMap AnimMontageUtils::groupById(QObject *root)
{
    QMap<QString,QObject*> ret;
    groupByIdImp(root,ret);
    return ret;
}

bool AnimMontageUtils::isBase(QString className, const QMetaObject *meta)
{
    while (meta) {
        if(meta->className() == className.toUtf8())
        {
            return true;
        }

        meta = meta->superClass();
    }
    return false;
}

QMetaObject::Connection DynamicConnect::connect(QObject *source, int signalIndex, QObject *receiver, SlotType slot,Qt::ConnectionType type)
{
    DynamicConnect* slotObj = new DynamicConnect();
    slotObj->func = slot;
    return QObjectPrivate::connect(source,signalIndex,receiver,slotObj,type);
}

void DynamicConnect::FuncImpl(int which, QSlotObjectBase *this_, QObject *receiver, void **args, bool *ret)
{
    auto This = static_cast<DynamicConnect*>(this_);
    if(which == QtPrivate::QSlotObjectBase::Operation::Call)
    {
        This->func(receiver,args,ret);
    }
    else if(which == QtPrivate::QSlotObjectBase::Compare)
    {
        *ret = false;
    }
    else if(which == QtPrivate::QSlotObjectBase::Destroy)
    {
        delete This;
    }
}
